<template>
  <div class="users-page">
    <!-- 页面标题和操作 -->
    <div class="page-header">
      <div class="header-left">
        <h1>用户管理</h1>
        <p>管理系统用户账号和权限</p>
      </div>
      <div class="header-right">
        <el-button type="primary" :icon="Plus" @click="handleCreate">
          新增用户
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input
            v-model="searchForm.email"
            placeholder="请输入邮箱"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.role" placeholder="请选择角色" clearable>
            <el-option label="全部" value="" />
            <el-option
              v-for="role in roles"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="handleReset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户表格 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <div class="header-actions">
            <el-button
              type="danger"
              :icon="Delete"
              :disabled="!selectedUsers.length"
              @click="handleBatchDelete"
            >
              批量删除
            </el-button>
            <el-button :icon="Download" @click="handleExport">
              导出
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="users"
        @selection-change="handleSelectionChange"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :size="40" :src="row.avatar">
              {{ row.username.charAt(0).toUpperCase() }}
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column label="角色" min-width="120">
          <template #default="{ row }">
            <el-tag
              v-for="role in row.roles"
              :key="role.id"
              :type="getRoleTagType(role.name)"
              size="small"
              class="role-tag"
            >
              {{ role.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-value="active"
              inactive-value="inactive"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="last_login" label="最后登录" width="160">
          <template #default="{ row }">
            {{ formatTime(row.last_login) }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              :icon="View"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              type="warning"
              size="small"
              :icon="Edit"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="用户详情"
      width="600px"
      :before-close="handleCloseDetail"
    >
      <div v-if="currentUser" class="user-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="头像">
            <el-avatar :size="60" :src="currentUser.avatar">
              {{ currentUser.username.charAt(0).toUpperCase() }}
            </el-avatar>
          </el-descriptions-item>
          <el-descriptions-item label="用户名">
            {{ currentUser.username }}
          </el-descriptions-item>
          <el-descriptions-item label="邮箱">
            {{ currentUser.email }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentUser.status === 'active' ? 'success' : 'danger'">
              {{ currentUser.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="角色" :span="2">
            <el-tag
              v-for="role in currentUser.roles"
              :key="role.id"
              :type="getRoleTagType(role.name)"
              class="role-tag"
            >
              {{ role.name }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="最后登录">
            {{ formatTime(currentUser.last_login) }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatTime(currentUser.created_at) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 用户编辑对话框 -->
    <el-dialog
      v-model="editVisible"
      :title="isEdit ? '编辑用户' : '新增用户'"
      width="600px"
      :before-close="handleCloseEdit"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input
            v-model="editForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select
            v-model="editForm.roles"
            multiple
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="role in roles"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio value="active">启用</el-radio>
            <el-radio value="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            {{ submitLoading ? '保存中...' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  Plus,
  Search,
  Refresh,
  Delete,
  Download,
  View,
  Edit,
  Upload
} from '@element-plus/icons-vue'
import { usersApi, rolesApi } from '@/api'
import type { User, Role } from '@/api'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const detailVisible = ref(false)
const editVisible = ref(false)
const isEdit = ref(false)
const selectedUsers = ref([])
const currentUser = ref(null)

const tableRef = ref<any>()
const editFormRef = ref<FormInstance>()

// 搜索表单
const searchForm = reactive({
  username: '',
  email: '',
  status: '',
  role: ''
})

// 编辑表单
const editForm = reactive({
  id: '',
  username: '',
  email: '',
  password: '',
  roles: [],
  status: 'active'
})

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 用户列表
const users = ref([
  {
    id: 1,
    username: 'admin',
    email: 'admin@example.com',
    avatar: '',
    status: 'active',
    roles: [{ id: 1, name: '超级管理员' }],
    last_login: '2024-01-15 10:30:00',
    created_at: '2024-01-01 00:00:00'
  },
  {
    id: 2,
    username: 'editor',
    email: 'editor@example.com',
    avatar: '',
    status: 'active',
    roles: [{ id: 2, name: '编辑者' }],
    last_login: '2024-01-15 09:15:00',
    created_at: '2024-01-02 00:00:00'
  },
  {
    id: 3,
    username: 'viewer',
    email: 'viewer@example.com',
    avatar: '',
    status: 'inactive',
    roles: [{ id: 3, name: '查看者' }],
    last_login: '2024-01-14 16:20:00',
    created_at: '2024-01-03 00:00:00'
  }
])

// 角色列表
const roles = ref([
  { id: 1, name: '超级管理员' },
  { id: 2, name: '编辑者' },
  { id: 3, name: '查看者' }
])

// 表单验证规则
const editRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
  ],
  roles: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 方法
const handleSearch = () => {
  pagination.page = 1
  loadUsers()
}

const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    email: '',
    status: '',
    role: ''
  })
  handleSearch()
}

const handleCreate = () => {
  isEdit.value = false
  editVisible.value = true
  resetEditForm()
}

const handleView = (row: any) => {
  currentUser.value = row
  detailVisible.value = true
}

const handleEdit = (row: any) => {
  isEdit.value = true
  editVisible.value = true
  Object.assign(editForm, {
    id: row.id,
    username: row.username,
    email: row.email,
    password: '',
    roles: row.roles.map((r: any) => r.id),
    status: row.status
  })
}

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${row.username}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里调用删除API
    ElMessage.success('删除成功')
    loadUsers()
  } catch {
    // 用户取消删除
  }
}

const handleBatchDelete = async () => {
  if (!selectedUsers.value.length) {
    ElMessage.warning('请选择要删除的用户')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里调用批量删除API
    ElMessage.success('批量删除成功')
    selectedUsers.value = []
    loadUsers()
  } catch {
    // 用户取消删除
  }
}

const handleStatusChange = async (row: any) => {
  try {
    // 这里调用状态更新API
    ElMessage.success(`用户状态已${row.status === 'active' ? '启用' : '禁用'}`)
  } catch (error) {
    // 恢复原状态
    row.status = row.status === 'active' ? 'inactive' : 'active'
    ElMessage.error('状态更新失败')
  }
}

const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

const handleSelectionChange = (selection: any[]) => {
  selectedUsers.value = selection
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  loadUsers()
}

const handlePageChange = (page: number) => {
  pagination.page = page
  loadUsers()
}

const handleSubmit = async () => {
  if (!editFormRef.value) return

  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 这里调用保存API
        await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟API调用
        
        ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
        editVisible.value = false
        loadUsers()
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const handleCloseDetail = () => {
  detailVisible.value = false
  currentUser.value = null
}

const handleCloseEdit = () => {
  editFormRef.value?.resetFields()
  editVisible.value = false
  resetEditForm()
}

const resetEditForm = () => {
  Object.assign(editForm, {
    id: '',
    username: '',
    email: '',
    password: '',
    roles: [],
    status: 'active'
  })
}

const loadUsers = async () => {
  loading.value = true
  try {
    const response = await usersApi.getUsers({
      page: pagination.page,
      pageSize: pagination.size,
      keyword: searchForm.username,
      status: searchForm.status,
      roleId: searchForm.role
    })
    
    if (response.code === 200) {
      users.value = response.data.list
      pagination.total = response.data.total
    } else {
      ElMessage.error(response.message || '加载用户数据失败')
    }
    
  } catch (error) {
    console.warn('用户API调用失败，使用模拟数据:', error)
    
    // 模拟数据
    const mockUsers = [
      {
        id: 1,
        username: 'admin',
        email: 'admin@example.com',
        avatar: '',
        status: 'active',
        roles: [{ id: 1, name: '超级管理员' }],
        last_login: '2024-01-15 10:30:00',
        created_at: '2024-01-01 00:00:00'
      },
      {
        id: 2,
        username: 'editor',
        email: 'editor@example.com',
        avatar: '',
        status: 'active',
        roles: [{ id: 2, name: '编辑者' }],
        last_login: '2024-01-15 09:15:00',
        created_at: '2024-01-02 00:00:00'
      },
      {
        id: 3,
        username: 'viewer',
        email: 'viewer@example.com',
        avatar: '',
        status: 'inactive',
        roles: [{ id: 3, name: '查看者' }],
        last_login: '2024-01-14 16:20:00',
        created_at: '2024-01-03 00:00:00'
      }
    ]
    
    users.value = mockUsers
    pagination.total = mockUsers.length
    
    ElMessage.warning('使用模拟数据，请检查后端服务')
  } finally {
    loading.value = false
  }
}

const getRoleTagType = (roleName: string) => {
  const typeMap: Record<string, string> = {
    '超级管理员': 'danger',
    '编辑者': 'warning',
    '查看者': 'info'
  }
  return typeMap[roleName] || 'primary'
}

const formatTime = (time: string) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

// 组件挂载时加载数据
onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.users-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-left h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-left p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.role-tag {
  margin-right: 4px;
  margin-bottom: 4px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.user-detail {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .users-page {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .header-actions {
    flex-direction: column;
    width: 100%;
  }
}
</style>